# -*- coding: utf-8 -*-

"""
@File    : auto_check.py
@Author  : xubin
@Time    : 2022/8/8 10:01
@Desc    :
"""
import random

import feapder
from feapder.utils.tools import send_msg, get_current_date
from config import DOMAIN_LIST, YOUYUN_USER, YOUYUN_PWD
from feapder.utils.log import log

"""
优云自动签到
"""


def get_vpn():
    vpn_list = [
        {
            'http': 'http://192.168.1.77:12341',
            'https': 'http://192.168.1.77:12341',
        },
        {
            'http': 'http://192.168.1.77:12342',
            'https': 'http://192.168.1.77:12342',
        },
        {
            'http': 'http://192.168.1.77:12343',
            'https': 'http://192.168.1.77:12343',
        },
        {
            'http': 'http://192.168.1.77:12344',
            'https': 'http://192.168.1.77:12344',
        },
        {
            'http': 'http://192.168.1.77:12345',
            'https': 'http://192.168.1.77:12345',
        },
        {
            'http': 'http://192.168.1.77:12346',
            'https': 'http://192.168.1.77:12346',
        },
        {
            'http': 'http://192.168.1.77:12347',
            'https': 'http://192.168.1.77:12347',
        },
        {
            'http': 'http://192.168.1.77:12348',
            'https': 'http://192.168.1.77:12348',
        },
        {
            'http': 'http://192.168.1.77:12349',
            'https': 'http://192.168.1.77:12349',
        }
    ]
    return random.choice(vpn_list)


class AutoCheckin(feapder.AirSpider):
    domain = None
    user = YOUYUN_USER
    pwd = YOUYUN_PWD

    def start_callback(self):
        for domain in DOMAIN_LIST:
            response = feapder.Request(url=domain, method='GET', proxies=get_vpn(), retry_times=3).get_response()
            if response.status_code == 200:
                self.domain = domain
                return

    def start_requests(self):
        log.info(f'有效ULR:{self.domain}')
        url = f"{self.domain}/auth/login"
        data = {
            "email": self.user,
            "passwd": self.pwd,
            "code": "",
            "remember_me": "on"
        }
        yield feapder.Request(url, data=data, method="POST", use_session=True)

    def download_midware(self, request):
        request.proxies = get_vpn()
        return request

    def parse(self, request, response):
        log.info(response.json.get('msg'))
        url = f"{self.domain}/user/checkin"
        yield feapder.Request(url, method="POST", use_session=True, callback=self.checkin)

    def checkin(self, request, response):
        msg = f"{get_current_date()},\n{response.json.get('msg')}"
        log.info(msg)
        send_msg(msg)
